<template>
  <el-dialog
    :title="upload.title"
    v-model="upload.open"
    :show-close="false"
    width="400px"
    append-to-body
    :close-on-click-modal="false"
    v-dialog-drag
  >
    <el-upload
      ref="uploadRef"
      :limit="1"
      accept=".xlsx, .xls"
      :headers="upload.headers"
      :action="upload.url"
      :disabled="upload.isUploading"
      :on-progress="handleFileUploadProgress"
      :on-success="handleFileSuccess"
      :auto-upload="false"
      :data="upload.data"
      drag
    >
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <template #tip>
        <div class="el-upload__tip text-center">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link
            type="primary"
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            @click="importTemplate"
            >下载模板</el-link
          >
        </div>
      </template>
    </el-upload>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确定</el-button>
        <el-button @click="upload.open = false">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { ElMessage, ElUpload } from 'element-plus'
import { getToken } from '@/utils/auth'
import { template } from 'lodash'

interface UploadData {
  couponsId: number | null
}

interface UploadConfig {
  open: boolean
  title: string
  isUploading: boolean
  headers: { Authorization: string }
  url: string
  data: UploadData
}

interface Props {
  apiUrl?: string
}

const props = withDefaults(defineProps<Props>(), {
  apiUrl: '',
})

const emit = defineEmits<{
  success: []
}>()

const uploadRef = ref<InstanceType<typeof ElUpload>>()

// 用户导入参数
const upload = reactive<UploadConfig>({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: '',
  // 是否禁用上传
  isUploading: false,
  // 设置上传的请求头部
  headers: { Authorization: 'Bearer ' + getToken() },
  // 上传的地址
  url: '',
  data: {
    couponsId: null,
  },
})

/** 导入按钮操作 */
const handleImport = () => {
  upload.title = '用户导入'
  upload.open = true
}

/** 下载模板操作 */
const importTemplate = () => {
  // Assuming download is a global function available
  // You might need to import or define this function
  // download(
  //   props.apiUrl,
  //   {},
  //   `user_template_${new Date().getTime()}.xlsx`
  // )
}

// 文件上传中处理
const handleFileUploadProgress = (event: any, file: any, fileList: any) => {
  upload.isUploading = true
}

// 文件上传成功处理
const handleFileSuccess = (response: any, file: any, fileList: any) => {
  if (response.code == 200) {
    upload.open = false
    ElMessage.success('操作成功')
    emit('success')
  } else {
    ElMessage.error(response.msg)
  }
  upload.isUploading = false
  uploadRef.value?.clearFiles()
}

// 提交上传文件
const submitFileForm = () => {
  uploadRef.value?.submit()
}

defineExpose({
  handleImport,
})
</script>

<style lang="scss" scoped></style>
